package com.qk.management.aop;

import cn.hutool.json.JSONUtil;
import com.qk.common.Result;
import com.qk.common.util.CurrentUserContextHolders;
import com.qk.entity.OperateLog;
import com.qk.management.mapper.OperateLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @author Just、倾城
 * @created 2025-10-17
 * @description
 * 定义日志记录切面
 */
@Component
@Aspect
@Slf4j
public class LogRecordAspect {

    @Autowired
    private OperateLogMapper opreateLogMapper;
    @Pointcut("@annotation(com.qk.management.aop.LogAnno)")
    public void pt(){}

    @Around("pt()")
    public Object around(ProceedingJoinPoint jpj) {
        Object result = null;
        try {
            long start = System.currentTimeMillis();
            result = jpj.proceed();
            long end = System.currentTimeMillis();


            OperateLog operateLog = OperateLog.builder()
                    .className(jpj.getTarget().getClass().getName())
                    .methodName(jpj.getSignature().getName())
                    .methodParams(JSONUtil.toJsonStr(jpj.getArgs()))
                    .returnValue(JSONUtil.toJsonStr(result))
                    .costTime(end - start)
                    .operateTime(LocalDateTime.now())
                    .operateUserId(CurrentUserContextHolders.get())
                    .build();
            opreateLogMapper.insert(operateLog);
        } catch (Throwable e) {
            result = Result.error("您得操作失败,请稍后试");
            log.error("操作失败:{}", e.getMessage());
        }
        return result;
    }

}
